# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# Author     ：hu_cl
# Date       ：2022/3/16 15:50
# File       : file_info.py
# Description： 文件信息
"""
import datetime
import os
import signal
import subprocess
import re

video_type = ['asf', 'avi', 'dat', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'qt', 'rm', 'rmvb',
              'ts', 'vob', 'wmv']
audio_type = ['cda', 'wav', 'mp3', 'aif', 'aiff', 'mid', 'wma', 'ra', 'vqf', 'ape']
image_type = ['xbm', 'tif', 'pjp', 'svgz', 'jpg', 'jpeg', 'ico', 'tiff', 'gif', 'svg', 'jfif', 'webp',
              'png', 'bmp', 'pjpeg', 'avif', 'dwg']
file_type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'wps', 'pdf', 'iso', 'rar', 'zip', '7z', 'html']
other_type = []


def run_cmd(cmd_string, timeout=15):
    p = subprocess.Popen(cmd_string, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True, close_fds=True,
                         start_new_session=True)

    sys_format = 'utf-8'

    try:
        (msg, errs) = p.communicate(timeout=timeout)
        ret_code = p.poll()
        if ret_code:
            code = 1
            msg = "[Error]Called Error ： " + str(msg.decode(sys_format))
        else:
            code = 0
            msg = str(msg.decode(sys_format))
    except subprocess.TimeoutExpired:
        # 注意：不能只使用p.kill和p.terminate，无法杀干净所有的子进程，需要使用os.killpg
        p.kill()
        p.terminate()
        os.killpg(p.pid, signal.SIGTERM)

        # 注意：如果开启下面这两行的话，会等到执行完成才报超时错误，但是可以输出执行结果
        # (outs, errs) = p.communicate()
        # print(outs.decode('utf-8'))

        code = 1
        msg = "[ERROR]Timeout Error : Command '" + cmd_string + "' timed out after " + str(timeout) + " seconds"
    except Exception as e:
        code = 1
        msg = "[ERROR]Unknown Error : " + str(e)

    return code, msg


def sum_flow(data):
    file_flow = data.strip(' ')
    if 'kB/s' in file_flow:
        flow = float(file_flow.strip('kB/s')) * 10 ** 3
    elif 'MB/s' in file_flow:
        flow = float(file_flow.strip('MB/s')) * 10 ** 6
    elif 'GB/s' in file_flow:
        flow = float(file_flow.strip('GB/s')) * 10 ** 9
    else:
        print('例外', file_flow)
        flow = float(file_flow.strip('B/s'))

    return flow

def main():
    start_time = datetime.datetime.now()
    print('starttime', start_time)
    cmd_string = 'rsync -rtlvWP  t1/ t2'
    code, msg = run_cmd(cmd_string)
    pattern1 = re.compile('([^<>/\\\|:""\*\?]+\.\w+\s)')  # 匹配文件名
    pattern2 = re.compile('(\d+\.\d*[a-zA-Z]B/s)')  # 匹配网速
    pattern3 = re.compile('(\s(?:\d+,?)+\s)')  # 文件大小
    odl_msg = msg
    msg = msg.replace('\r', '').replace('\n', '').split(')')
    file_dict = {'type': 'file', 'size': 0, 'flow': 0}
    image_dict = {'type': 'image', 'size': 0, 'flow': 0}
    audio_dict = {'type': 'audio', 'size': 0, 'flow': 0}
    video_dict = {'type': 'video', 'size': 0, 'flow': 0}
    other_dict = {'type': 'other', 'size': 0, 'flow': 0}
    other_count = 0
    file_count = 0
    image_count = 0
    audio_count = 0
    video_count = 0
    try:
        for i in msg:
            if '100%' in i:
                file = pattern1.findall(i)
                file_flow = pattern2.findall(i)[-1]
                file_size = pattern3.findall(i)[-1]
                if not file:
                    data = re.sub(r'[ \t].*', "", i.strip(' '))
                    file = re.sub(r'.*\/', "", data)
                    other_dict['size'] = other_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                    other_count = other_count + 1
                    other_dict['flow'] = other_dict['flow'] + sum_flow(file_flow)
                else:
                    file = file[-1]
                    file_ext = str(file.strip(' ').split('.')[-1]).lower()
                    if file_ext in file_type:
                        file_dict['size'] = file_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                        file_count = file_count + 1
                        file_dict['flow'] = file_dict['flow'] + sum_flow(file_flow)
                    elif file_ext in video_type:
                        video_dict['size'] = video_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                        video_count = video_count + 1
                        video_dict['flow'] = video_dict['flow'] + sum_flow(file_flow)
                    elif file_ext in audio_type:
                        audio_dict['size'] = audio_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                        audio_count = audio_count + 1
                        audio_dict['flow'] = audio_dict['flow'] + sum_flow(file_flow)
                    elif file_ext in image_type:
                        image_dict['size'] = image_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                        image_count = image_count + 1
                        image_dict['flow'] = image_dict['flow'] + sum_flow(file_flow)
                    else:
                        other_dict['size'] = other_dict['size'] + float(file_size.strip(' ').replace(',', ''))
                        other_count = other_count + 1
                        other_dict['flow'] = other_dict['flow'] + sum_flow(file_flow)

                if (not file) or (not file_flow) or (not file_size):
                    print(i)

        file_dict['flow'] = (file_dict['flow'] / file_count) if file_count else 0
        image_dict['flow'] = (image_dict['flow'] / image_count) if image_count else 0
        audio_dict['flow'] = (audio_dict['flow'] / audio_count) if audio_count else 0
        video_dict['flow'] = (video_dict['flow'] / video_count) if video_count else 0
        other_dict['flow'] = (other_dict['flow'] / other_count) if other_count else 0

    except Exception as exp:
        print(exp)
        print(i)

    file_info = [file_dict, image_dict, audio_dict, video_dict, other_dict]
    print(file_info)

    end_time = datetime.datetime.now()
    print('finished_time', end_time - start_time)


if __name__ == '__main__':
    main()
